// pages/news/detail.js
Page({
  data: {
    article: null,
    loading: true,
    error: false
  },

  onLoad(options) {
    console.log('详情页接收参数:', options)
    if (!options || !options.id) {
      this.setData({ error: true })
      wx.showToast({
        title: '缺少文章ID参数',
        icon: 'none'
      })
      return
    }
    
    const id = String(options.id).trim()
    if (!/^\d{5,}$/.test(id)) {
      this.setData({ error: true })
      wx.showToast({
        title: '文章ID必须为5位以上数字',
        icon: 'none'
      })
      return
    }
    
    this.loadArticleDetail(id)
  },

  loadArticleDetail(id) {
    if (!/^\d{5,}$/.test(id)) {
      this.setData({ 
        loading: false,
        error: true 
      })
      wx.showToast({
        title: '文章ID必须为5位以上数字',
        icon: 'none'
      })
      return Promise.reject('无效的文章ID格式')
    }

    this.setData({ loading: true, error: false })
    const { articleApi } = require('../../utils/api')
    return articleApi.getArticleDetail(id)
      .then(res => {
        console.log('原始API响应:', res)
        // 直接使用响应数据
        const data = res
        console.log('处理后数据:', data)
        if (!data) {
          console.error('API返回数据为空')
          throw new Error('API返回数据为空')
        }
        this.setData({
          article: {
            id: data.news_id || data.newsId || data.id,
            title: data.title || '无标题',
            content: data.content_html || data.content_text || data.contentHtml || data.content || '暂无内容',
            category: data.category || '未分类',
            pubTime: data.pubTime || new Date().toISOString(),
            viewCount: data.viewCount || 0,
            image: data.image || data.imageUrl || ''
          },
          loading: false
        })
        wx.hideLoading()
        wx.setNavigationBarTitle({
          title: data.title || '新闻详情'
        })
      })
      .catch(err => {
        console.error('获取新闻详情失败:', err)
        this.setData({
          loading: false,
          error: true
        })
        wx.showToast({
          title: '获取新闻详情失败',
          icon: 'none'
        })
      })
  },

  onShareAppMessage() {
    if (this.data.article) {
      return {
        title: this.data.article.title,
        path: `/pages/news/detail?id=${this.data.article.id}`
      }
    }
    return {
      title: '新闻详情',
      path: '/pages/news/detail'
    }
  },

  onRetry() {
    const id = this.options.id
    if (id) {
      this.loadArticleDetail(id)
    }
  },

  formatTime(dateString) {
    if (!dateString) return ''
    const date = new Date(dateString)
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
  }
})
